package com.nondo.rdp.stock.service.impl;

import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.stock.domain.StockChoose;
import com.nondo.rdp.stock.repository.StockChooseRepository;
import com.nondo.rdp.stock.service.StockChooseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class StockChooseServiceImpl implements StockChooseService {
    @Autowired
    StockChooseRepository stockChooseRepository;

    @Override
    public StockChoose findOne(Long id) {
        return this.stockChooseRepository.findOne(id);
    }

    @Override
    public StockChoose save(StockChoose stockChoose) {
        return this.stockChooseRepository.save(stockChoose);
    }

    @Override
    public void update(StockChoose stockChoose) {
        this.stockChooseRepository.save(stockChoose);
    }

    @Override
    public void delete(Long id) {
        this.stockChooseRepository.deleteById(id);
    }

    @Override
    public StockChoose findByUser(User user) {
        return this.stockChooseRepository.findByUser(user);
    }

    @Override
    public Page<StockChoose> findAll(Page<StockChoose> page, StockChoose stockChoose) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<StockChoose> dictPage = stockChooseRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();
            //搜索ID
            if (stockChoose.getId() != null && stockChoose.getId() != 0) {
                predicates.add(builder.equal(root.get("id"), stockChoose.getId()));
            }
            //搜索用户
            if (stockChoose.getUser() != null && stockChoose.getUser() != null) {
                predicates.add(builder.equal(root.get("user").get("id"), stockChoose.getUser().getId()));
            }
            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<StockChoose>(dictPage);
    }

    @Override
    public StockChoose findByUserAndCode(User user, String code) {
        return this.stockChooseRepository.findByUserAndCode(user, code);
    }
}